// pages/schedule/schedule.js
import Toast from 'tdesign-miniprogram/toast/index';

var isClicked = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showConfirm: false,
    confirmBtn: {
      content: '确定',
      variant: 'base'
    },
    cntItem: '',
    visible: false,
    scheduleList: [],
    cntDate: new Date().getTime(),
    value: new Date().getTime(),
    minDate: new Date(2023, 4, 1).getTime(),
    maxDate: new Date(2023, 12, 31).getTime(),
    format(day) {
      const {
        date
      } = day;
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const curDate = date.getDate();
      day.suffix = '';
      if (year === 2023) {
        if (month === 1) {
          const map = {
            1: '元旦节',
            14: '小年',
            21: '除夕',
            22: '春节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 2) {
          const map = {
            5: '元宵节',
            14: '情人节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 3) {
          const map = {
            8: '国际妇女节',
            12: '植树节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 4) {
          const map = {
            1: '愚人节',
            5: '清明节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 5) {
          const map = {
            1: '劳动节',
            4: '青年节',
            12: '国际护士节',
            14: '母亲节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 6) {
          const map = {
            1: '国际儿童节',
            18: '父亲节',
            22: '端午节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 7) {
          const map = {
            1: '建党节',
            7: '七夕情人节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 8) {
          const map = {
            1: '建军节',
            22: '七夕情人节',
            30: '中元节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 9) {
          const map = {
            10: '教师节',
            29: '中秋节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 10) {
          const map = {
            1: '国庆节',
            23: '重阳节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 11) {
          const map = {
            1: '万圣节',
            13: '寒衣节',
            23: '感恩节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        } else if (month === 12) {
          const map = {
            22: '冬至节',
            25: '圣诞节',
          };
          if (curDate in map) {
            day.prefix = map[curDate];
            day.suffix = '';
            day.className = 'is-holiday';
          }
        }

        // 二十四节气
        const solarTerms = {
          '小寒': '01-05',
          '大寒': '01-20',
          '立春': '02-04',
          '雨水': '02-19',
          '惊蛰': '03-06',
          '春分': '03-21',
          '清明': '04-05',
          '谷雨': '04-20',
          '立夏': '05-06',
          '小满': '05-21',
          '芒种': '06-06',
          '夏至': '06-21',
          '小暑': '07-07',
          '大暑': '07-23',
          '立秋': '08-08',
          '处暑': '08-23',
          '白露': '09-08',
          '秋分': '09-23',
          '寒露': '10-08',
          '霜降': '10-23',
          '立冬': '11-07',
          '小雪': '11-22',
          '大雪': '12-07',
          '冬至': '12-22',
        };
        let m = month < 10 ? '0' + month : month
        let d = curDate < 10 ? '0' + curDate : curDate
        const solarTermDates = Object.values(solarTerms);
        if (solarTermDates.includes(`${m}-${d}`)) {
          const index = solarTermDates.indexOf(`${month}-${curDate}`);
          const solarTermName = Object.keys(solarTerms)[index];
          day.prefix = solarTermName;
          day.suffix = '';
          day.className = 'is-solar-term';
        }
      }
      return day;
    },
  },
  showDialog(e) {
    if (isClicked) return
    isClicked = true
    let item = e.currentTarget.dataset.item
    console.log('删除', item)
    this.setData({
      showConfirm: true,
      cntItem: item
    });
  },
  confirmDialog() {
    this.setData({
      showConfirm: false
    });
    this.deleteSchdule()
  },
  closeDialog() {
    this.setData({
      showConfirm: false
    });
    isClicked = false
  },
  addSchdule() {
    wx.navigateTo({
      url: "/pages/schedule/schedule-setting/index",
    })
  },
  handleSelect(e) {
    const {
      value,
      entireValue
    } = e.detail;
    console.log(value);
    console.log(entireValue);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  getScheduleList() {
    let _this = this
    wx.cloud.callFunction({
      name: 'getSchedule'
    }).then(res => {
      console.log('data==>', res)
      _this.setData({
        scheduleList: res.result.data.data
      })
      this.getCntScheduleList()
    })
  },
  handleSelect(e) {
    const {
      value
    } = e.detail;
    console.log(value);
    this.getCntScheduleList(new Date(value))
  },
  getDateStrByTimestamp(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  getCntScheduleList(currentDate = new Date()) {
    let scheduleList = this.data.scheduleList;

    currentDate.setHours(0, 0, 0, 0);

    const cntScheduleList = [];
    for (let i = 0; i < scheduleList.length; i++) {
      const item = scheduleList[i];
      const beginDate = new Date(item.begin_date);
      beginDate.setHours(0, 0, 0, 0);
      const endDate = new Date(item.end_date);
      endDate.setHours(0, 0, 0, 0);
      if (beginDate.getTime() <= currentDate.getTime() && endDate.getTime() >= currentDate.getTime()) {
        cntScheduleList.push(item);
      }
    }
    this.setData({
      cntScheduleList
    })
  },
  deleteSchdule() {
    let item = this.data.cntItem
    let scheduleList = this.data.scheduleList
    let cntScheduleList = this.data.cntScheduleList
    let _this = this
    console.log('删除', item.title)
    wx.cloud.callFunction({
      name: 'updateSchedule',
      data: {
        _id: item._id,
        status: 0,
        flag: 'delete'
      }
    }).then(res => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '已删除日程【' + item.title + ']',
        theme: 'success',
      });
      const index = scheduleList.findIndex((obj) => obj._id === item._id);
      if (index >= 0) {
        scheduleList.splice(index, 1);
      }
      const index2 = cntScheduleList.findIndex((obj) => obj._id === item._id);
      console.log('index',index)
      console.log('index2',index2)
      if (index2 >= 0) {
        cntScheduleList.splice(index2, 1);
      }
      // 更新数据
      _this.setData({
        scheduleList: scheduleList,
        cntScheduleList: cntScheduleList
      });

    }).catch(err => {
      console.error(err)
    })

    isClicked = false
  },
  goUpdateSchdule(e) {
    if (isClicked) return
    var item = e.currentTarget.dataset.item
    wx.setStorageSync('cntSchdule', item)
    wx.setStorageSync('updateSchdule', true)
    wx.navigateTo({
      url: '/pages/schedule/schedule-setting/index',
    })
    isClicked = false
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getScheduleList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})